import pymysql
from config import config


class DBHandler:

    def __init__(self,
                 host=config.mysql_host,
                 port=config.mysql_port,
                 user=config.mysql_user,
                 password=config.mysql_password,
                 database=config.mysql_database,
                 charset=config.charset,
                 **kwargs):
        self.db = pymysql.connect(host=host, port=port, user=user, password=password,
                                  database=database, charset=charset)
        self.course = self.db.cursor()  # 获取游标,游标用来操作sql语句

    def query(self, sql):
        try:
            self.course.execute(sql)
            self.db.commit()
            return self.course.fetchall()
        except Exception as e:
            self.db.rollback()
            self.course.fetchall()
            raise e
        finally:
            self.course.close()

    def clone(self):
        self.db.close()


if __name__ == '__main__':
    import re
    db = DBHandler()
    with open('../data/table.sql', 'r', encoding='utf-8') as f:
        sql = ''.join(re.findall('INSERT.+.;', f.read()))
    db.query(sql)
